package com.seth.myapplication.surface;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.seth.myapplication.R;
import com.seth.myapplication.adapter.ItemAdapter;
import com.seth.myapplication.bean.Bounty;
import com.seth.myapplication.bean.Rewords;
import com.seth.myapplication.bean.User;
import com.seth.myapplication.service.NetWorkService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import static java.lang.Thread.sleep;

/**
 * Created by Seth on 2017/10/11.
 */

public class page3Fragment extends Fragment {
    public static final int ACCEPT_RERSULT = 23;
    public static final String RECEIVER_INIT = "com.seth.myapplication.surface.GET_TASK";

    private View view;
    private EditText search_tab;

    private RecyclerView mRecyclerView;
    private List<String> infos = new ArrayList<>();
    private MaterialRefreshLayout refreshTask;
    // private List<String> blockInfo = new ArrayList<>();
    private ItemAdapter mMyAdapter;
    private TaskBroadCast msgReceiver;
    private ArrayList<Bounty> freshList;
    private ArrayList<Rewords> rewords = new ArrayList<>();
    private ItemAdapter taskItemAdapter;
    private int page = 1;
    private int count = 10;
    private int rewordIndex = 0;
    private NetWorkService mService;

    @Override
    public void onAttach(Context context) {

        //动态注册广播接收器
        msgReceiver = new TaskBroadCast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(RECEIVER_INIT);
        context.registerReceiver(msgReceiver, intentFilter);
        super.onAttach(context);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_get_task, container, false);

        initView(view);

        initEvent();


        return view;

    }

    private void initEvent() {
        FreshTasks();
        refreshTask.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                FreshTasks();

            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                //load more refreshing...
            }
        });
    }

    private void FreshTasks() {
        String data_str = "{\"page\":\""+page+"\","
                +"\"status\":\"" +1+"\","
                +"\"count\":\""+count+"\"}";

        String url = "http://139.199.9.252/look/time";

        mService = new NetWorkService(getActivity(),RECEIVER_INIT);
        mService.freshTask(data_str,url,"page");
    }

    private void initView(View view) {

        search_tab = (EditText) view.findViewById(R.id.search_txt);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.list_task);
        refreshTask = (MaterialRefreshLayout) view.findViewById(R.id.refresh_task);

        taskItemAdapter = new ItemAdapter(getContext());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        Drawable draw = getResources().getDrawable(R.drawable.ic_search);

        draw.setBounds(0,0,60,60);
        search_tab.setCompoundDrawables(draw,null,null,null);
        mRecyclerView.setAdapter(taskItemAdapter);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(msgReceiver);
        super.onDestroy();
    }


    class TaskBroadCast extends BroadcastReceiver
    {
        HashMap<String,User> users = new HashMap<>();
        @Override
        public void onReceive(Context context, Intent intent)
        {
            String msg = intent.getStringExtra("result");
            if("success".equals(msg)){

                rewords = (ArrayList<Rewords>) intent.getSerializableExtra("rewords");
                Iterator<Rewords>  i = rewords.iterator();
                Log.i("ReworsdRespond","开始获取用户信息");
                //将悬赏的用户以id为key存入map
                while (i.hasNext()){
                    Rewords r = i.next();
                    Log.i("ReworsdRespond","用户id"+r.getUsrId());
                    users.put(r.getUsrId()+"",null);
                }
                //获取有关key的Set
                Iterator<String> iterator = users.keySet().iterator();
                while(iterator.hasNext()){
                    mService.getUser(iterator.next());
                    Log.i("ReworsdRespond","加载用户");
                }

            }else if("userinfo".equals(msg)){
                //添加同步互斥
                synchronized(page3Fragment.class) {
                    User user = (User) intent.getSerializableExtra("usrInfo");
                    Log.i("ReworsdRespond", "读取用户id" + user.getUsrId());
                    //写到这里未完待续
                    if (user != null) {
                        rewordIndex++;
                        users.put(user.getUsrId() + "", user);
                        Log.i("UPDATE_REWORDS", user.getUsrId() + user.getNickname());
                    }
                }
                if(rewordIndex==users.size()){
                    rewordIndex=0;
                    Log.i("ReworsdRespond","读取用户id完毕");
                    for(int i=0;i<rewords.size();i++){
                        Log.i("UPDATE_REWORDS",rewords.get(i).getUsrId()+"更新");
                        User user1 = users.get(rewords.get(i).getUsrId()+"");
                        Log.i("UPDATE_REWORDS",user1.getUsrId()+"");
                        rewords.get(i).setSeter(user1);

                    }
                    refreshTask.finishRefresh();
                    taskItemAdapter.setList(rewords);
                    taskItemAdapter.notifyDataSetChanged();
                    onResume();
                }
            }else{
                Log.i("ReworsdRespond","失败"+msg);
                refreshTask.finishRefresh();
                taskItemAdapter.setList(rewords);
                taskItemAdapter.notifyDataSetChanged();
                Toast.makeText(context, "获取悬赏失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onActivityResult(int resquestCode, int resultCode, Intent data){
        if(resultCode != Activity.RESULT_OK){
            return ;
        }
        if(resquestCode == ACCEPT_RERSULT){
            String msg = data.getStringExtra("msg");
            if("success".equals(msg)){
                Rewords r = (Rewords) data.getSerializableExtra("reword");
                rewords.remove(rewords.indexOf(r));
                taskItemAdapter.setList(rewords);
                taskItemAdapter.notifyDataSetChanged();

            }else{

            }
        }
    }

}
